<?php

class weixin {

    var $_third_login_mod;

    function __construct() {
        $this->_third_login_mod = & m('third_login');
    }

    /**
     * 通过参数获取  access_token
     */
    
    function curl($appid, $secret) {
        //access_token 生命周期
        $wxconfig_mod = & m('wxconfig');
        $wxconfig = $wxconfig_mod->get_info_user(0);
        $data['access_token'] = $wxconfig['access_token'];
        $time = time();
        if ($time - $wxconfig['last_update'] > 7200) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
            $data = request_get($url);
            $data = json_decode($data, true);
            
            if($data['access_token']){
                $wxconfig_mod->edit($wxconfig['w_id'],array('last_update'=>$time,'access_token'=>$data['access_token']));
            }
        }
        return $data;
    }

    /**
     * 创建菜单
     */
    function curl_menu($ACCESS_TOKEN, $param) {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $ACCESS_TOKEN;
        $data = request_post($url, $param);
        $data = json_decode($data, true);
        return $data;
    }

    //通过 openid 获取用户的基本信息
    function get_info($openid) {
        //获取系统设置的appid 与  SECRET
        $appid = Conf::get('payment_wx_appid');
        $appsecret = Conf::get('payment_wx_secret');
        if (empty($appid) || empty($appsecret)) {
            return;
        }
        $ACCESS_LIST = $this->curl($appid, $appsecret);
        $access_token = $ACCESS_LIST['access_token'];
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $data = request_get($url);
        $data = json_decode($data, true);
        return $data;
    }

    //获取生成的二维码 带scene_id
    function get_qrcode($scene_id) {
        $data =array();
        
        $QR = ROOT_PATH.'/data/files/mall/portrait/qrcode_' . $scene_id . '.jpg';

        $refer_qrcode = SITE_URL.'/data/files/mall/portrait/qrcode_' . $scene_id . '.jpg';
        
        //存在文件
        if (!is_file($QR)) {
            //获取系统设置的appid 与  SECRET
            $appid = Conf::get('payment_wx_appid');
            $appsecret = Conf::get('payment_wx_secret');
            if (empty($appid) || empty($appsecret)) {
                return;
            }
            $ACCESS_LIST = $this->curl($appid, $appsecret);
            $access_token = $ACCESS_LIST['access_token'];

            $json_arr = array('action_name' => 'QR_LIMIT_SCENE', 'action_info' => array('scene' => array('scene_id' => $scene_id)));
            $json_data = json_encode($json_arr);
            $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $access_token;
            $json_res = request_post($url, $json_data);
            $json = json_decode($json_res);

            if ($json->ticket) {
                $ticket_url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode($json->ticket);
                $imageinfo = request_get($ticket_url);
                $time = time();
                $url = $_SERVER['HTTP_HOST'];

                $local_file = fopen($QR, 'a');
                if (false !== $local_file) {
                    if (false !== fwrite($local_file, $imageinfo)) {
                        fclose($local_file);
                    }
                }
            } else {
                return '获取二维码失败';
            }
        }
        
        //合并图层
        $default_qrcode_bg = ROOT_PATH.'/data/files/mall/settings/default_qrcode_bg.jpg';#背景图
        $refer_qrcode_logo = ROOT_PATH.'/data/files/mall/portrait/qrcode_' . $scene_id . '_logo.png';

        if (!is_file($refer_qrcode_logo)) {
            //有背景图
            if (is_file($default_qrcode_bg)) {
                $QR = imagecreatefromstring(file_get_contents($QR));
                $logo = imagecreatefromstring(file_get_contents($default_qrcode_bg));
                $QR_width = imagesx($QR);
                $QR_height = imagesy($QR);
                imagecopyresampled($logo, $QR, 170, 400, 0, 0, 180, 180, $QR_width, $QR_height);

                //此处是给图片载入文字
                $member_mod = &m('member');
                $member_info = $member_mod->get($scene_id);
                $text = '您的好友:' . $member_info['user_name'];
                $textcolor = imagecolorallocate($logo, 0, 0, 255);
                $font_file = ROOT_PATH.'/data/files/mall/settings/ziti.ttf';
                imagefttext($logo, 30, 0, 100, 80, $textcolor, $font_file, mb_convert_encoding($text, 'html-entities', 'UTF-8'));
                imagepng($logo, $refer_qrcode_logo);
            } else {
                return '没有背景图';
            }
        }
        
        return array('refer_qrcode'=>$refer_qrcode,'refer_qrcode_bg'=>$refer_qrcode_logo);
    }
    
    

    /**
     * 下单通知 发送给卖家   
     * OPENTM200746866
     * 订单提交成功通知
     */
    function message_template_order($order_info) {
        $template_id = '5EmJRnZlbewD4fAEN22fk-MXTwM3V5-RyrdqdjhstLQ';
        $url = site_url() . '/index.php?app=member';



        $data = array(
            "first" => array(
                "value" => "您好，您有新订单。",
                "color" => "#173177"
            ),
            "keyword1" => array(
                "value" => $info['user_name'],
                "color" => "#173177"
            ),
            "keyword2" => array(
                "value" => date('Y-m-d H:s:d', time()),
                "color" => "#173177"
            ),
            "remark" => array(
                "value" => "感谢使用，请注意账号安全。",
                "color" => "#173177"
            )
        );
        $this->message_template_send($info['user_id'], $template_id, $url, $data);
    }

    // 密码修改 微信通知
    function message_template_change_password($info) {
        $template_id = 'J1Yct3Ojho8YpVefgs_U693N4YIz0r77cLSThTUhYEk';
        $url = site_url() . '/index.php?app=member';

        $member_mod = &m('member');
        $info = $member_mod->get($info['user_id']);
        if (empty($info)) {
            return;
        }

        $data = array(
            "first" => array(
                "value" => "您好,您的登录帐号发生一次登录操作",
                "color" => "#173177"
            ),
            "keyword1" => array(
                "value" => $info['user_name'],
                "color" => "#173177"
            ),
            "keyword2" => array(
                "value" => date('Y-m-d H:s:d', time()),
                "color" => "#173177"
            ),
            "remark" => array(
                "value" => "感谢使用，请注意账号安全。",
                "color" => "#173177"
            )
        );
        $this->message_template_send($info['user_id'], $template_id, $url, $data);
    }

    // 登录微信提醒通知
    function message_template_login($info) {

        $template_id = 'J1Yct3Ojho8YpVefgs_U693N4YIz0r77cLSThTUhYEk';
        $url = site_url() . '/index.php?app=member';

        $data = array(
            "first" => array(
                "value" => "您好,您的登录帐号发生一次登录操作",
                "color" => "#173177"
            ),
            "keyword1" => array(
                "value" => $info['user_name'],
                "color" => "#173177"
            ),
            "keyword2" => array(
                "value" => date('Y-m-d H:s:d', time()),
                "color" => "#173177"
            ),
            "remark" => array(
                "value" => "感谢使用，请注意账号安全。",
                "color" => "#173177"
            )
        );
        $this->message_template_send($info['user_id'], $template_id, $url, $data);
    }

    
    function get_openid($user_id) {
        //获得此订单用户的唯一 针对于 third_name 为 weixin  OPENID  
        $third_login = $this->_third_login_mod->get("user_id='$user_id' and third_name='weixin'");
        $openid = $third_login['openid'];
        return $openid;
    }

    function get_access_token() {
        $appid = Conf::get('payment_wx_appid');
        $appsecret = Conf::get('payment_wx_secret');
        if (empty($appid) || empty($appsecret)) {
            return;
        }

        $ACCESS_LIST = $this->curl($appid, $appsecret);
        $accessToken = $ACCESS_LIST['access_token'];
        return $accessToken;
    }

    /**
     * 发送模板消息
     * @param type $accessToken
     * @param type $touser
     * @param type $template_id
     * @param type $url
     * @param type $data
     * @param type $topcolor
     */
    function message_template_send($user_id, $template_id, $url, $data, $topcolor = '#173177') {
        //根据用户ID 获取 用户的 openid 用于发送模板消息
        $touser = $this->get_openid(intval($user_id));
        if (empty($touser)) {
            return;
        }

        $accessToken = $this->get_access_token();
        if (empty($accessToken)) {
            return;
        }

        $template = array(
            'touser' => $touser,
            'template_id' => $template_id,
            'url' => $url,
            'topcolor' => $topcolor,
            'data' => $data
        );
        $json_template = json_encode($template);
        $post_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $accessToken;
        $dataRes = request_post($post_url, $json_template);
        if (isset($dataRes['errcode']) && $dataRes['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }

}

?>
